package com.yichi.adapter;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.yichi.MainActivity;
import com.yichi.R;
import com.yichi.device_bean.BatteryStore;
import com.yichi.device_bean.BatteryStoreType;
import com.yichi.service.DeviceService;
import com.yichi.util.ToastUtil;

import java.util.Comparator;
import java.util.List;

public class BatteryAdapter extends RecyclerView.Adapter<BatteryAdapter.BatteryHolder> {

    public List<BatteryStore> batteryStoreList;
    public Context context;

    public List<BatteryStore> getbatteryStoreList() {
        return batteryStoreList;
    }

    public void setBatteryType(List<BatteryStore> batteryStoreList) {
        this.batteryStoreList = batteryStoreList;
    }

    public BatteryAdapter(List<BatteryStore> batteryStoreList, Context context) {
        this.context = context;
        this.batteryStoreList = batteryStoreList;
    }

    @NonNull
    @Override
    public BatteryHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_battery, parent, false);
        return new BatteryHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BatteryHolder holder, @SuppressLint("RecyclerView") int position) {
        holder.storeNo.setText(batteryStoreList.get(position).getStoreNo() + "");
        if (batteryStoreList.get(position).getStoreType() == BatteryStoreType.battery_store_type_storage) {
            holder.storeType.setText("存储区");
        } else if (batteryStoreList.get(position).getStoreType() == BatteryStoreType.battery_store_type_recharge) {
            holder.storeType.setText("充电区");
        } else if (batteryStoreList.get(position).getStoreType() == BatteryStoreType.battery_store_type_fault) {
            holder.storeType.setText("故障区");
        } else if (batteryStoreList.get(position).getStoreType() == BatteryStoreType.battery_store_type_input) {
            holder.storeType.setText("存电口");
        } else if (batteryStoreList.get(position).getStoreType() == BatteryStoreType.battery_store_type_output) {
            holder.storeType.setText("取电口");
        }
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {

            private Dialog selectDialog;

            @Override
            public boolean onLongClick(View view) {
                Dialog selectDialog = new Dialog(context);
                selectDialog.setContentView(R.layout.dialog_layout_select);
                selectDialog.setCanceledOnTouchOutside(false);
                selectDialog.setCancelable(false);
                selectDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//设置dialog默认背景为透明
                selectDialog.show();

                LinearLayout ll_set = selectDialog.findViewById(R.id.ll_set);
                LinearLayout ll_del = selectDialog.findViewById(R.id.ll_del);
                LinearLayout ll_cancel = selectDialog.findViewById(R.id.ll_cancel);
                //编辑
                ll_set.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        selectDialog.dismiss();
                        showSetDialog(position);
                    }
                });
                //删除
                ll_del.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        builder.setTitle("提示")
                                .setMessage("确认要删除吗？")
                                .setPositiveButton("确认", (dialog, which) -> {
                                    batteryStoreList.remove(position);
                                    DeviceService.inst.saveData();
                                    notifyDataSetChanged();
                                    selectDialog.dismiss();
                                })
                                .setNegativeButton("取消", (dialog, which) -> {
                                })
                                .show(); // 显示对话框
                    }
                });
                //取消
                ll_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        selectDialog.dismiss();
                    }
                });
                return false;
            }

        });
    }

    public void showSetDialog(int position) {
        final int[] selecteType = {0};

        BatteryStore batteryStoreModel;
        if (position == -1) {
            batteryStoreModel = null;
        } else {
            batteryStoreModel = batteryStoreList.get(position);
        }

        Dialog selectDialog = new Dialog(context);
        selectDialog.setContentView(R.layout.dialog_layout_edit);
        selectDialog.setCanceledOnTouchOutside(false);
        selectDialog.setCancelable(false);
        selectDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//设置dialog默认背景为透明
        selectDialog.show();

        TextView tv_title = selectDialog.findViewById(R.id.tv_title);
        if (position == -1) {
            tv_title.setText("添加");
        } else {
            tv_title.setText("修改");
        }

        TextView bt_cancel = selectDialog.findViewById(R.id.bt_cancel);
        TextView bt_save = selectDialog.findViewById(R.id.bt_save);

        EditText et_num = selectDialog.findViewById(R.id.et_num);
        Spinner spinner = selectDialog.findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context, R.array.your_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        final Integer[] oldStoreNoArr = new Integer[1];
        if (position == -1) {
            et_num.setText("");
            spinner.setSelection(0);
        } else {
            oldStoreNoArr[0] = batteryStoreModel.getStoreNo();
            et_num.setText(batteryStoreModel.getStoreNo().toString());
            spinner.setSelection(batteryStoreModel.getStoreType());
        }

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int selectePosition, long id) {
                selecteType[0] = selectePosition;
                if (selectePosition == 0) {
                    TextView tv = (TextView) view;
                    tv.setTextColor(context.getResources().getColor(R.color.hint));
                }
                // Handle selection here.
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Handle no selection here if needed.
            }
        });

        //取消
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectDialog.dismiss();
            }
        });
        //保存
        bt_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String num = et_num.getText().toString().trim();
                if (num.equals("")) {
                    Toast.makeText(context, "请电池仓编号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (selecteType[0] == 0) {
                    Toast.makeText(context, "请选择电池仓类型", Toast.LENGTH_SHORT).show();
                    return;
                }

                Integer numInt = Integer.parseInt(num);
                if (position == -1) {//新增
                    //编号存在
                    boolean exists = batteryStoreList.stream().anyMatch(store -> store != null && numInt.equals(store.getStoreNo()));
                    if (exists) {
                        Toast.makeText(context, "该编号已存在", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    BatteryStore batteryStore = new BatteryStore(numInt, selecteType[0]);
                    batteryStoreList.add(batteryStore);
                    //排序保存
                    batteryStoreList.sort(Comparator.comparing(BatteryStore::getStoreNo));
                    DeviceService.inst.saveData();
                } else {//修改
                    //编号存在
                    boolean exists = batteryStoreList.stream().anyMatch(store -> !store.getStoreNo().equals(oldStoreNoArr[0]) && store.getStoreNo().equals(numInt));
                    if (exists) {
                        Toast.makeText(context, "该编号已存在", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    batteryStoreList.get(position).setStoreNo(Integer.parseInt(num));
                    batteryStoreList.get(position).setStoreType(selecteType[0]);
                    //排序保存
                    batteryStoreList.sort(Comparator.comparing(BatteryStore::getStoreNo));
                    DeviceService.inst.saveData();
                }

                notifyDataSetChanged();
                selectDialog.dismiss();
            }
        });
    }

    @Override
    public int getItemCount() {
        return batteryStoreList.size();
    }

    static class BatteryHolder extends RecyclerView.ViewHolder {
        TextView storeNo;
        TextView storeType;

        BatteryHolder(View itemView) {
            super(itemView);
            storeNo = itemView.findViewById(R.id.storeNo);
            storeType = itemView.findViewById(R.id.storeType);
        }
    }
}